﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.ServiceModel.Activation;
using System.Web;
using System.Web.Security;

using Core;
using Core.Domain;
using Core.Domain.Repositories;
using Core.Domain.Model;


namespace Developmentalmadness
{
	[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
	public class SSOService : ISSOService, ISSOPartnerService
	{

        
		#region ISSOService Members

		/// <summary>
		/// Returns the client's current identity token so it can
		/// assert its identity to a partner application
		/// </summary>
		/// <returns>encrypted identity token</returns>
        /// 
        public SSOToken Requestsite(string webname)
		{
			// default response
			SSOToken token = new SSOToken
			{
				Token = string.Empty,
				Status = "DENIED"
			};

			// verify we've already authenticated the client
			if (HttpContext.Current.Request.IsAuthenticated)
			{
				// get the current identity
				FormsIdentity identity = (FormsIdentity)HttpContext.Current.User.Identity;

				// we'll send the client its own FormsAuthenticationTicket, but 
				// we'll encrypt it so only we can read it when the partner app
				// needs to validate who the client is through our service
                string name = identity.Ticket.Name;
                string pass = identity.Ticket.CookiePath;


                if ((string.CompareOrdinal(name, "hai") == 0) && (string.CompareOrdinal(pass,"123") == 0))
                {
                    if ((string.CompareOrdinal(webname, "Hello") == 0))
                    {

                        token.Token = FormsAuthentication.Encrypt(identity.Ticket);
                        token.Status = "SUCCESS";
                    
                    }
                
                }
				
			}

			return token;
		}
        public SSOToken RequestToken()
		{
			// default response
			SSOToken token = new SSOToken
			{
				Token = string.Empty,
				Status = "DENIED"
			};

			// verify we've already authenticated the client
			if (HttpContext.Current.Request.IsAuthenticated)
			{
				// get the current identity
				FormsIdentity identity = (FormsIdentity)HttpContext.Current.User.Identity;

				// we'll send the client its own FormsAuthenticationTicket, but 
				// we'll encrypt it so only we can read it when the partner app
				// needs to validate who the client is through our service
                string name = identity.Ticket.Name;
                string pass = identity.Ticket.CookiePath;


               

                        token.Token = FormsAuthentication.Encrypt(identity.Ticket);
                        token.Status = "SUCCESS";
                    
                    
                
                
				
			}

			return token;
		}

		/// <summary>
		/// Log client out of SSO service
		/// </summary>
		/// <returns>true if successful</returns>
		public bool Logout()
		{
			HttpContext.Current.Session.Clear();
			FormsAuthentication.SignOut();
			HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName);
			cookie.Expires = DateTime.Now.AddDays(-10000.0);
			HttpContext.Current.Response.Cookies.Add(cookie);
			return true;
		}

		/// <summary>
		/// Log client into SSO service
		/// </summary>
		/// <returns></returns>
        /// 
        public SSOToken Registry(string username,string password,string mail) {

            SSOToken token = new SSOToken
            {
                Token = string.Empty,
                Status = "DENIED"
            };
            try
            {

                Customer tam = new Customer();

                tam.id = System.Guid.NewGuid();
                tam.name = username;
                tam.password = password;
                tam.mail = mail;
                tam.createdate = System.DateTime.Now;
                IRepository<Customer> pro = new CustomerRepository();
                pro.Save(tam);

                // mock data to simulate passing around additional data
                Guid temp = Guid.NewGuid();

                // manage cookie lifetime
                DateTime issueDate = DateTime.Now;
                DateTime expireDate = issueDate.AddMonths(1);

                // create the ticket and protect it
                FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, username, issueDate, expireDate, true, temp.ToString(), password);
                string protectedTicket = FormsAuthentication.Encrypt(ticket);

                // save the protected ticket with a cookie
                HttpCookie authorizationCookie = new HttpCookie(FormsAuthentication.FormsCookieName, protectedTicket);
                authorizationCookie.Expires = expireDate;

                // protect the cookie from session hijacking
                authorizationCookie.HttpOnly = true;

                // write the cookie to the response stream
                HttpContext.Current.Response.Cookies.Add(authorizationCookie);

                // update the response to indicate success
                token.Status = "SUCCESS";
                token.Token = protectedTicket;
            }catch(Exception e){
            
            
            }
            return token;
        
        }

        
		public SSOToken Login(string username, string password)
		{
			// default response
			SSOToken token = new SSOToken
			{
				Token = string.Empty,
				Status = "DENIED"
			};

			// authenticate user
            if (test_user(username, password)==true)
			{
                
				// mock data to simulate passing around additional data
				Guid temp = Guid.NewGuid();

				// manage cookie lifetime
				DateTime issueDate = DateTime.Now;
				DateTime expireDate = issueDate.AddMonths(1);

				// create the ticket and protect it
                FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, username, issueDate, expireDate, true, temp.ToString(), password);
				string protectedTicket = FormsAuthentication.Encrypt(ticket);

				// save the protected ticket with a cookie
				HttpCookie authorizationCookie = new HttpCookie(FormsAuthentication.FormsCookieName, protectedTicket);
				authorizationCookie.Expires = expireDate;

				// protect the cookie from session hijacking
				authorizationCookie.HttpOnly = true;

				// write the cookie to the response stream
				HttpContext.Current.Response.Cookies.Add(authorizationCookie);

				// update the response to indicate success
				token.Status = "SUCCESS";
				token.Token = protectedTicket;
			}

			return token;
		}

        private bool test_user(string n, string p) {

            IRepository<Customer> pro = new CustomerRepository();
            var model = pro.GetAll();
            foreach (var item in model) {

                if ((string.CompareOrdinal(item.name, n) == 0) && (string.CompareOrdinal(item.password, p) == 0))
                {
                    return true;
                }
            }


            return false;
        }

		/// <summary>
		/// Confirms the client is signed into SSO service
		/// </summary>
		/// <param name="token">the client's asserted identity token</param>
		/// <returns>user's identity information</returns>
		public SSOUser ValidateToken(string token)
		{
			try
			{
				// if we can decrypt the ticket then it wasn't tampered with
				// and token is valid
				FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(token);
                
                
				return new SSOUser { 
					Username = ticket.Name, 
					SessionToken = new Guid(ticket.UserData),
                    UserPassword=ticket.CookiePath
                   
				};
			}
			catch
			{
				// validation failed
				return new SSOUser { 
					Username = string.Empty, 
					SessionToken = Guid.Empty,
                   UserPassword=string.Empty
				};
			}

           
		}

		#endregion
	}
}
